package com.laizt.client.util;

import com.aspose.cells.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class TestOffice {
    private static final Logger logger = LoggerFactory.getLogger(TestOffice.class.getName());

    public static void main(String[] args) {
        String path = "C:\\Users\\14593\\Desktop\\testexcel\\整件-HD6N硬盘盒组装作业指导书(V1.１).xlsx";

        excel2pdf(path,path.replace(".xlsx",".pdf"));

    }

    public static void toPdf(){



        String path = "D:\\整件-HD6N硬盘盒组装作业指导书(V1.１).xlsx";
        excel2pdf(path,path.replace(".xlsx",".pdf"));

    }


    public static boolean getCellLicense() {
        boolean result = false;
        try {

            String s = "<License><Data><Products><Product>Aspose.TotalforJava</Product><Product>Aspose.WordsforJava</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";

            //File file = ResourceUtils.getFile("classpath:license.xml");
            InputStream is = new ByteArrayInputStream(s.getBytes());
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void excel2pdf(String officePath,String pdfPath) {
        if (!getCellLicense()) {
            return ;
        }
        try {
            long old = System.currentTimeMillis();
            Workbook wb = new Workbook(officePath);// 原始excel路径
            File file = new File(pdfPath);// 输出路径
            FileOutputStream fileOS = new FileOutputStream(file);
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
            long now = System.currentTimeMillis();
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒/n" + "文件保存在:" + file.getPath()); //转化过程耗时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    /**
     * 将目录中的文件转pdf
     * @param dir
     */
    public static String generateDirToPdf(String dir){
        File fl=new File(dir);
        String[] files=fl.list();
        File f=null;
        for(String file:files)
        {
            f=new File(fl,file);//注意,这里一定要写成File(fl,file)如果写成File(file)是行不通的,一定要全路径
            System.out.println("===>"+f.getName());



            if(f.isDirectory()){
                generateDirToPdf(f.getAbsolutePath());
            }else{
                String filename=f.getName();
                String  filePath = f.getAbsolutePath();
                System.out.println(filename);
                logger.info("文件名："+filename);
                logger.info("文件路径："+filePath);
                //将所有xls和xlsx文件转Pdf
                if(filename.contains(".xlsx")||filename.contains(".xls")){
                    convertOffice2PDF(filePath, dir);
                   // f.delete();//删除文件
                    return filePath;
                }
            }
        }
        return null;
    }

    /**
     * 利用libreOffice将office文档转换成pdf
     * @param inputFile  目标文件地址
     * @param pdfFile    输出文件夹
     * @return
     */
    public static boolean convertOffice2PDF(String inputFile, String pdfFile){
        long start = System.currentTimeMillis();
        String command;
        boolean flag;
        String osName = System.getProperty("os.name");
        if (osName.contains("Windows")) {
            command = "cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }else {
            command = "libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + inputFile + " --outdir " + pdfFile;
        }
        flag = executeLibreOfficeCommand(command);
        long end = System.currentTimeMillis();
        logger.info("用时:{} ms", end - start);
        return flag;
    }

    /**
     * 执行command指令
     * @param command
     * @return
     */
    public static boolean executeLibreOfficeCommand(String command) {
        logger.info("开始进行转化.......");
        Process process;// Process可以控制该子进程的执行或获取该子进程的信息
        try {
            logger.debug("convertOffice2PDF cmd : {}", command);
            process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序，并返回与该子进程对应的Process对象实例。
            // 下面两个可以获取输入输出流
//            InputStream errorStream = process.getErrorStream();
//            InputStream inputStream = process.getInputStream();
        } catch (IOException e) {
            logger.error(" convertOffice2PDF {} error", command, e);
            return false;
        }
        int exitStatus = 0;
        try {
            exitStatus = process.waitFor();// 等待子进程完成再往下执行，返回值是子线程执行完毕的返回值,返回0表示正常结束
            // 第二种接受返回值的方法
            int i = process.exitValue(); // 接收执行完毕的返回值
            logger.debug("i----" + i);
        } catch (InterruptedException e) {
            logger.error("InterruptedException  convertOffice2PDF {}", command, e);
            return false;
        }
        if (exitStatus != 0) {
            logger.error("convertOffice2PDF cmd exitStatus {}", exitStatus);
        } else {
            logger.debug("convertOffice2PDF cmd exitStatus {}", exitStatus);
        }
        process.destroy(); // 销毁子进程
        logger.info("转化结束.......");
        return true;
    }


}
